package com.example.final_project.service.impl;

import com.example.final_project.entity.Inventory;
import com.example.final_project.mapper.InventoryMapper;
import com.example.final_project.service.InventoryService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class InventoryServiceImpl implements InventoryService {

    @Autowired
    private InventoryMapper inventoryMapper;

    @Override
    @Transactional
    public boolean add(Inventory inventory) {
        return inventoryMapper.insert(inventory) > 0;
    }

    @Override
    @Transactional
    public boolean update(Inventory inventory) {
        return inventoryMapper.update(inventory) > 0;
    }

    @Override
    @Transactional
    public boolean delete(Long id) {
        return inventoryMapper.deleteById(id) > 0;
    }

    @Override
    @Transactional
    public boolean deleteByBookId(Long bookId) {
        return inventoryMapper.deleteByBookId(bookId) > 0;
    }

    @Override
    public Inventory getById(Long id) {
        return inventoryMapper.selectById(id);
    }

    @Override
    public Integer getStockByBookId(Long bookId) {
        Inventory inventory = inventoryMapper.selectByBookId(bookId);
        return inventory != null ? inventory.getQuantity() : null;
    }

    @Override
    @Transactional
    public boolean deductStock(Long bookId, Integer quantity) {
        Inventory inventory = inventoryMapper.selectByBookId(bookId);
        if (inventory != null && inventory.getQuantity() >= quantity) {
            inventory.setQuantity(inventory.getQuantity() - quantity);
            return inventoryMapper.update(inventory) > 0;
        }
        return false; // 库存不足或图书不存在
    }

    @Override
    @Transactional
    public boolean addStock(Long bookId, Integer quantity) {
        Inventory inventory = inventoryMapper.selectByBookId(bookId);
        if (inventory != null) {
            inventory.setQuantity(inventory.getQuantity() + quantity);
            return inventoryMapper.update(inventory) > 0;
        }
        return false; // 图书库存记录不存在
    }

    @Override
    public Inventory getByBookId(Long bookId) {
        return inventoryMapper.selectByBookId(bookId);
    }

    @Override
    public PageInfo<Inventory> getList(String bookName, String isbn, String author, Long publisherId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Inventory> list = inventoryMapper.selectList(bookName, isbn, author, publisherId);
        return new PageInfo<>(list);
    }
} 